package com.app.mymusic.ui;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.app.mymusic.R;
import com.app.mymusic.adapter.SearchOnNetAdapter;
import com.app.mymusic.model.Mp3Info;
import com.app.mymusic.model.NetMusic;
import com.app.mymusic.utils.DownLoadUtil;
import com.app.mymusic.utils.LogUtil;
import com.app.mymusic.utils.MediaPlayerUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/8/4.
 */
public class SearchOnNetFragment extends Fragment {
    private RecyclerView mRecyclerView;
    private List<NetMusic.MusicInfo> mDatas=new ArrayList<NetMusic.MusicInfo>();
//    private NetMusic.MusicInfo musicInfo;
    private  List<Mp3Info>  lists=new ArrayList<Mp3Info>();
    private SearchOnNetAdapter mAdapter;
    private  Context context=getActivity();
    private final static int GET_URL=1;
    private Handler mHandler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case GET_URL:
//                    Mp3Info mp3Info=new Mp3Info();
//                    mp3Info.setTitle(musicInfo.getSongname());
//                    mp3Info.setArtist(musicInfo.getSingername());
//                    mp3Info.setDuration(musicInfo.getDuration()*1000);
//                    mp3Info.setHttpUrl(msg.obj.toString());
//                    mp3Info.setPath("");
//                    lists.add(mp3Info);
                break;
            }
        }
    };
    public SearchOnNetFragment() {
        super();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.showLog("SearchOnNetFragment-onCreate");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_searchonnet,container);
        mRecyclerView= (RecyclerView) view.findViewById(R.id.ser_recycler);
        mAdapter=new SearchOnNetAdapter(R.layout.fragment_searchonnet_item,lists);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        return view;
    }
    @Override
    public void onStart() {
        super.onStart();
        String str=getActivity().getIntent().getStringExtra("keyword");
        searchMusic(str);
    }

    private void searchMusic(String keyword) {
        Retrofit retrofit=new Retrofit.Builder().baseUrl("http://apis.baidu.com/geekery/music/")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        interSearch iSearch=retrofit.create(interSearch.class);
        iSearch.get(keyword,"10","1").subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<NetMusic>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Snackbar.make(mRecyclerView,"错误："+e,Snackbar.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(NetMusic mInfo) {
                       int code= mInfo.getCode();
                        if(code==0)
                        {
                            mDatas.addAll(mInfo.getData().getData());
                            convertToMp3Info(mDatas);

                        }

                    }
                });
    }

    private void convertToMp3Info(List<NetMusic.MusicInfo> mDatas) {
        for(NetMusic.MusicInfo m:mDatas)
        {
            Mp3Info mp3Info=new Mp3Info();
            mp3Info.setTitle(m.getSongname());
            mp3Info.setArtist(m.getSingername());
            mp3Info.setDuration(m.getDuration()*1000);
            mp3Info.setHash(m.getHash());
            mp3Info.setPath("");
            getSongUrl(m.getHash(),mp3Info);
        }
    }

    private void  getSongUrl(String hash, final Mp3Info mp3Info) {
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://apis.baidu.com/geekery/music/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        interSearch iSearch=retrofit.create(interSearch.class);
        iSearch.getUrl(hash)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<NetMusic>() {
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable e) {

                    }
                    @Override
                    public void onNext(NetMusic n) {
                        mp3Info.setHttpUrl(n.getData().getUrl());
                        lists.add(mp3Info);
                        mAdapter.notifyDataSetChanged();
                        mRecyclerView.addOnItemTouchListener(new ItemListener());
                        mRecyclerView.addOnItemTouchListener(new ItemChildListener());
                    }
                });
    }

    class ItemListener extends OnItemChildClickListener
    {

        @Override
        public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
            context=getActivity();
            MediaPlayerUtil util=new MediaPlayerUtil(context,lists,i);
            util.play();
            startActivity(new Intent(context,FullSreenActivity.class));
        }
    }

    private class ItemChildListener extends OnItemChildClickListener {

        @Override
        public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
            switch (view.getId())
            {
                case R.id.ser_more:
                    Mp3Info m=lists.get(i);
                    String path="";
                    path=m.getHttpUrl().replace("http://song.music.response.itmf.cn/","");
                    DownLoadUtil.downLoadMusic(path,m.getTitle()+".mp3",m);
                    startActivity(new Intent(getActivity(),DownLoadActivity.class));
                    break;
            }
        }
    }

    public interface interSearch
    {
        @Headers("apikey:13e982978120a8e0218bd279e0632036")
        @GET("query")
        Observable<NetMusic> get(@Query("s") String s, @Query("size") String size, @Query("page") String page);

        @Headers("apikey:13e982978120a8e0218bd279e0632036")
        @GET("playinfo")
        Observable<NetMusic> getUrl(@Query("hash") String hash);

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
    }
    @Override
    public void onStop() {
        super.onStop();
    }
}
